<template>
  <div class="page-miH page-bgBack">
    <TableTitle>
      <template slot="title">考勤合计人数：{{ total }}人</template>
    </TableTitle>
    <div class="xq-form-wrapper" style="padding:0 24px 24px 24px;">
      <!-- <a-row style="margin-bottom: 24px;" type="flex" align="middle" justify="space-between">
        <a-col>
          <a-range-picker
            valueFormat="YYYY-MM-DD"
            :allow-clear="false"
            v-model="Time"
            style="width: 240px;margin-right:12px;"
            @change="getCheckCardList"
          />
          <a-input-search
            v-model="searchForm.empInfoName"
            allow-clear
            placeholder="搜索员工"
            style="width: 180px;margin-right:12px;"
            @search="nameChange"
          />
          <a-tree-select
            style="width: 180px;margin-right:12px;"
            placeholder="请选择岗位"
            :tree-data="depInfoOptions"
            allow-clear
            @change="handleDepChange"
          />
        </a-col>
      </a-row> -->
      <!-- <a-row type="flex" justify="space-between" align="middle">
        <a-col>考勤合计人数：{{ total }}人</a-col>
        <a-col>
          <a-button style="margin-right:12px" :disabled="!selectedRowKeys.length" type="primary" @click="onShow(1)">批量导出</a-button>
          <a-button type="primary" @click="onShow(2)" :disabled="tableData.length <= 0">
            导出报表
          </a-button>
          <a-button style="margin-right:12px" :disabled="!selectedRowKeys.length" type="primary" @click="download(1)">批量导出</a-button>
          <a-button type="primary" @click="download(2)" :disabled="!tableData.length">
            导出报表
          </a-button>
        </a-col>
      </a-row> -->

      <a-spin :spinning="spinning" class="xq-form-content">
        <TableBody
          selectHead
          selection
          tableName="checkTable"
          :selectedRowKeys.sync="selectedRowKeys"
          :source="tableData"
          :headerRowID="'sortable_list'"
          :columns="columns"
          @onReload="getCheckCardList"
          @onExport="() => onShow(1)"
          @onExportAll="() => onShow(2)"
        >
          <template slot="search">
            <a-range-picker valueFormat="YYYY-MM-DD" :allow-clear="false" style="width: 240px;" v-model="Time" @change="handleSearch" />
            <a-input-search
              v-model="searchForm.empInfoName"
              allow-clear
              placeholder="搜索员工"
              style="width: 180px;"
              @change="handleSearch"
            />
            <a-tree-select
              style="width: 180px;"
              placeholder="请选择岗位"
              :tree-data="depInfoOptions"
              allow-clear
              v-model="positionInfoIdArr"
              @change="handleDepChange"
            />
          </template>

          <template slot-scope="prop">
            <XqTable
              :class="prop.className"
              :components="prop.components"
              :columns="prop.columns"
              :scroll="{ x: prop.scrollWidth }"
              :customHeaderRow="
                () => {
                  return {
                    domProps: {
                      id: prop.headerRowID
                    }
                  };
                }
              "
              :customize="FormJson['config']['table']['customize']"
              :pagination="false"
              :dataSource="tableData"
              :rowSelection="
                FormJson['config']['table']['extend']['batch']
                  ? {
                      selectedRowKeys: selectedRowKeys,
                      onChange: onSelectChange
                    }
                  : null
              "
              class="xq-form-content-table"
            >
              <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
                <span :key="index">
                  {{ col.customTitle }}
                </span>
              </template>
              <!-- eslint-disable-next-line prettier/prettier -->
              <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
                <div v-if="col.dataIndex === 'arriveOne.arriveTime' || col.dataIndex === 'arriveTwo.arriveTime'" :key="index">
                  <span :class="record[col.dataIndex.split('.')[0]].arriveStatus === '正常' ? '' : 'errorColor'">
                    {{ text ? moment(text).format("HH:mm:ss") : "--" }}
                  </span>
                  <span :class="record[col.dataIndex.split('.')[0]].arriveStatus === '正常' ? '' : 'errorColor'">
                    （{{ record[col.dataIndex.split(".")[0]].arriveStatus ? record[col.dataIndex.split(".")[0]].arriveStatus : "--" }}）
                  </span>
                </div>
                <div v-else-if="col.dataIndex === 'arriveOne.arrivePlace' || col.dataIndex === 'arriveTwo.arrivePlace'" :key="index">
                  <span :class="record[col.dataIndex.split('.')[0]].rangeState === '1' ? '' : 'errorColor'">{{ text ? text : "--" }}</span>
                </div>
                <div v-else-if="col.dataIndex === 'leaveOne.leaveTime' || col.dataIndex === 'leaveTwo.leaveTime'" :key="index">
                  <span :class="record[col.dataIndex.split('.')[0]].leaveStatus === '正常' ? '' : 'errorColor'">
                    {{ text ? moment(text).format("HH:mm:ss") : "--" }}
                  </span>
                  <span :class="record[col.dataIndex.split('.')[0]].leaveStatus === '正常' ? '' : 'errorColor'">
                    （{{ record[col.dataIndex.split(".")[0]].leaveStatus ? record[col.dataIndex.split(".")[0]].leaveStatus : "--" }}）
                  </span>
                </div>
                <div v-else-if="col.dataIndex === 'leaveOne.leavePlace' || col.dataIndex === 'leaveTwo.leavePlace'" :key="index">
                  <span :class="record[col.dataIndex.split('.')[0]].rangeState === '1' ? '' : 'errorColor'">{{ text ? text : "--" }}</span>
                </div>
                <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
                  <a @click="() => enterDetail(record)">详情</a>
                </span>
                <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
              </template>
            </XqTable>
          </template>
        </TableBody>
        <div class="xq-form-content-pagination" style="margin-bottom: 24px">
          <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
          <a-pagination
            v-model="pageNo"
            :page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :page-size-options="['10', '20', '50', '100']"
            @change="onPageChange"
            @showSizeChange="onPageSizeChange"
          />
        </div>
      </a-spin>
    </div>
    <msg :visible.sync="visibleMsg" :jsonData="jsonData" @onUpdate="getCheckCardList" />
    <select-export :visible.sync="visible" @changeSE="changeSE" />
  </div>
</template>

<script>
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});

import { checkDay } from "@/api/check/checkCard";
import { getPositionInTree } from "@/api/department/position";
import moment from "moment";
import axios from "axios";
import qs from "qs";
import msg from "../component/msg";
import selectExport from "../component/select-export";

export default {
  mixins: [curdMixin],
  components: {
    selectExport,
    msg
  },
  data() {
    return {
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      companyId: "",
      depInfoOptions: [],
      selectedRowKeys: [],
      selectedRowKeysArr: [],
      searchForm: {
        companyId: "",
        positionInfoId: "",
        empInfoName: ""
      },
      visibleMsg: false,
      jsonData: {},
      visible: false,
      btnType: "",
      Time: [moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
      positionInfoIdArr: []
    };
  },

  created() {
    this.searchForm.companyId = this.$store.state.hr.companyId;
    this.companyId = this.$store.state.hr.companyId;
    getPositionInTree({ companyId: this.companyId }).then(res => {
      this.depInfoOptions = this.tree1(res.data[0].positionChildList, "positionChildList", true);
    });
    this.getCheckCardList();
  },

  methods: {
    handleSearch() {
      this.pageNo = 1;
      this.getCheckCardList();
    },
    handleDepChange(id) {
      this.searchForm.positionInfoId = id;
      this.pageNo = 1;
      this.getCheckCardList();
    },
    enterDetail(record) {
      this.jsonData = record;
      this.visibleMsg = true;
    },
    onSelectChange(selectedRowKeys) {
      const arr = [];
      selectedRowKeys.forEach(e => {
        arr.push(this.tableData[e].empInfoId);
      });
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowKeysArr = arr;
    },
    // 导出员工信息excel表
    download(i, v) {
      const token = this.$store.state.auth.token;
      let params = {};
      if (i === 2) {
        params = {
          ...this.searchForm,
          attendStart: this.Time[0],
          attendEnd: this.Time[1]
        };
      } else {
        params = {
          companyId: this.searchForm.companyId,
          attendStart: this.Time[0],
          attendEnd: this.Time[1],
          empInfoIdList: this.selectedRowKeysArr
        };
      }
      params.isError = v;
      axios({
        url: `/hr/api/v1/attendPunchRecords/exportAttendByDay`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          if (typeof res.data === "object" && res.data.type === "application/vnd.ms-excel") {
            const link = document.createElement("a");
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel"
            });
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", `${this.$store.state.hr.companyName}_` + "每日考勤报表" + ".xlsx");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          } else {
            this.$notification.warning({
              message: "提示",
              description: res.data.msg || "导出失败"
            });
          }
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },
    tree1(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          // item["selectable"] = false;
          this.tree1(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },

    async getCheckCardList() {
      try {
        this.spinning = true;
        const { data } = await checkDay({
          ...this.searchForm,
          attendStart: this.Time[0],
          attendEnd: this.Time[1],
          pageNo: this.pageNo,
          pageSize: this.pageSize
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        this.tableData.forEach(item => {
          const arrive = {
            arriveTime: null,
            arrivePlace: null,
            rangeState: null
          };
          const leave = {
            leaveTime: null,
            leavePlace: null,
            rangeState: null
          };
          item.arriveOne = item.arriveOne || arrive;
          item.leaveOne = item.leaveOne || leave;
          item.arriveTwo = item.arriveTwo || arrive;
          item.leaveTwo = item.leaveTwo || leave;
        });
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.pageNo = page;
      this.getCheckCardList();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getCheckCardList();
    },
    onShow(e) {
      this.visible = true;
      this.btnType = e;
    },
    changeSE(e) {
      if (e === 1) {
        this.download(this.btnType, false);
      }
      if (e === 2) {
        this.download(this.btnType, true);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.errorColor {
  color: var(--primary);
}
.noClickStatus {
  color: #999 !important;
}
.clickStatus {
  color: var(--primary);
  cursor: pointer;
}
.c_title {
  margin-bottom: 24px;
}
</style>
